import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';
import 'package:provider/provider.dart';
import 'package:flutterstudyapplast/business/viewmodels/article_collect_viwemodel.dart';
import 'package:flutterstudyapplast/common/event/events.dart';
import 'package:flutterstudyapplast/manager/app_manager.dart';
import 'package:flutterstudyapplast/ui/widget/article_item.dart';

class CollectArticlePage extends StatefulWidget {
  @override
  _CollectArticlePageState createState() => _CollectArticlePageState();
}

class _CollectArticlePageState extends State<CollectArticlePage> with AutomaticKeepAliveClientMixin{

  ScrollController _scrollController = ScrollController();
  bool _isHidden = false;
  int curPage = 0;
  StreamSubscription<CollectEvent> _collectEventListen;
  ArticleCollectViewModel _articleCollectViewModel = serviceLocator<ArticleCollectViewModel>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener((){
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixels = _scrollController.position.pixels;
      if(maxScroll == pixels && curPage < _articleCollectViewModel.totalCount){
        _getCollects();
      }
    });
    _collectEventListen = AppManager.eventBus.on<CollectEvent>().listen((event){
      if(mounted){
        if(!event.isCollect){
          _articleCollectViewModel.collects.removeWhere((item){
            return item.id == event.id;
          });
        }
      }
    });
    _getCollects();
  }

  @override
  void dispose(){
    _collectEventListen?.cancel();
    _scrollController.dispose();
    super.dispose();
  }

  _getCollects([bool refresh = false]) async{
    if(refresh){
      curPage = 0;
    }
    await _articleCollectViewModel.getCollects(curPage);
    _isHidden = true;
  }
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => _articleCollectViewModel,
      child: Consumer<ArticleCollectViewModel>(
        builder: (context,model,child){
          return Stack(
            children: <Widget>[
              Offstage(
                offstage: _isHidden,
                child: Center(child: CircularProgressIndicator(),),
              ),
              Offstage(
                offstage: !_isHidden || model.collects.isNotEmpty ,
                child: Center(child: Text("你还没有收藏内容..."),),
              ),
              Offstage(
                offstage: model.collects.isEmpty,
                child: RefreshIndicator(
                  onRefresh: ()=>_getCollects(true),
                  child: ListView.builder(
                    itemBuilder: (context,index)=>_buildItem(model.collects[index]),
                    itemCount: model.collects.length,
                    controller: _scrollController,
                    ///总是能滑动，因为数据少，listview无法滑动，
                    ///RefreshIndicator 就无法更新
                    physics: AlwaysScrollableScrollPhysics(),
                  ),
                ),
              )
            ],
          );
        },
      ),
    );
  }

  /// tab切换不重置
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  Widget _buildItem(item){//只收藏站内
    return ArticleItem(item);
  }
}
